package tech.xiaozai.rbac.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tech.xiaozai.common.CommonPage;
import tech.xiaozai.rbac.bo.UserBO;
import tech.xiaozai.rbac.custom.mapper.CustomUserMapper;
import tech.xiaozai.rbac.custom.po.UserPO;
import tech.xiaozai.rbac.mapper.SysUserMapper;
import tech.xiaozai.rbac.mapper.SysUserRoleRelationMapper;
import tech.xiaozai.rbac.mapstruct.UserMapStruct;
import tech.xiaozai.rbac.po.SysRolePermissionRelationKey;
import tech.xiaozai.rbac.po.SysUser;
import tech.xiaozai.rbac.po.SysUserRoleRelationExample;
import tech.xiaozai.rbac.po.SysUserRoleRelationKey;

import java.util.LinkedList;
import java.util.List;

/**
 * @author xiaozai
 * @version 1.0
 * @date 2020-09-14 10:29
 */
@Component
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private CustomUserMapper customUserMapper;

    @Autowired
    private SysUserRoleRelationMapper userRoleRelationMapper;

    @Override
    public SysUser getById(Long id){
        SysUser user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void update(SysUser user){
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void insert(SysUser user){
//        try {
//            sesssion.getConnection().setAutoCommit(false);
            userMapper.insertSelective(user);
//            session.getConnection().commit();
//        }catch (Exception e){
//            session.getConnection().rollback();
//        }
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public CommonPage<UserBO> page(Integer pageNum, Integer pageSize, SysUser model) {
        int begin = (pageNum-1)*pageSize;

        //现在查出来的是所有用户,分页就是取子集
        List<UserPO> list = customUserMapper.getAllLikeUsername(model==null?null:model.getUsername());
        List<UserPO> subList = list.subList(begin,begin+pageSize);

        return new CommonPage<UserBO>().setList(UserMapStruct.me.toBoList(subList))
                .setTotal((long) list.size())
                .setPageSize(pageSize)
                .setPageNum(pageNum)
                .setTotalPages( list.size()/pageSize);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRolesOfUser(Long userId, List<Long> roleIds) {
        SysUserRoleRelationExample example = new SysUserRoleRelationExample();
        example.createCriteria().andUidEqualTo(userId);
        List<SysUserRoleRelationKey> oldRoles = userRoleRelationMapper.selectByExample(example);
        List<Long> oldRoleIds = oldRoles.stream().mapToLong(SysUserRoleRelationKey::getRid).collect(LinkedList::new,List::add,List::addAll);
        List<Long> needDelete = new LinkedList<Long>(oldRoleIds);
        needDelete.removeAll(roleIds);
        if(!needDelete.isEmpty()){
            example.clear();
            example.createCriteria().andUidEqualTo(userId).andRidIn(needDelete);
            userRoleRelationMapper.deleteByExample(example);
        }

        roleIds.removeAll(oldRoleIds);
        if(!roleIds.isEmpty()){
            SysUserRoleRelationKey key = new SysUserRoleRelationKey();
            key.setUid(userId);
            roleIds.forEach(rid->{
                key.setRid(rid);
                userRoleRelationMapper.insertSelective(key);
            });
        }

    }


//    @Override
//    public CommonPage<UserBO> page(Integer pageNum, Integer pageSize, SysUser user){
//        PageHelper.startPage(pageNum,pageSize);
//
//
//
//        SysUserExample example=null;
//
//        if(user!=null) {
//
//            example = new SysUserExample();
//            SysUserExample.Criteria criteria = example.createCriteria();
//            if(user.getUsername()!=null&&user.getUsername().length()>0) {
//                criteria.andUsernameLike("%" + user.getUsername() + "%");
//            }
//            if(user.getState()!=null){
//                criteria.andStateEqualTo(user.getState());
//            }
//        }
//
//        Page<SysUser> page =  (Page<SysUser>)userMapper.selectByExample(example);
//
//        List<UserBO> list = UserMapStruct.me.toBoList(page.getResult());
//
//
//        return new CommonPage<UserBO>().setList(list)
//                .setPageNum(page.getPageNum())
//                .setPageSize(page.getPageSize())
//                .setTotal(page.getTotal())
//                .setTotalPages(page.getPages());
//
//    }





}
